﻿//========================================
// All rights reserved (C) 2017-2100
// CLR 版本：	4.0.30319.42000
// 命名空间:	SFJDService
// 文 件 名：	TransportReceive
// 作    者：	WooG
// 联系方式：	wooglle@163.com
// 创建时间：	2018/6/17 16:57:13
//========================================
using Common;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace SFJDService.TransportHandle
{
    public class TransportReceive
    {
        internal static TransportReceive instance;
        ClassTransportInfo transportInfo;
        int[] ports;
        static bool doing = false;
        Socket socketBack;
        //UdpClient udpBack;
        IPEndPoint pointBack;

        public TransportReceive(Guid guid, int[] ports, string iP, int portBack)
        {
            if (doing)
            {
                return;
            }
            else
            {
                doing = true;
                this.ports = ports;
                transportInfo = Runtime.xmlDownload.GetTransInfo(guid);
                socketBack = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                socketBack.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
                pointBack = new IPEndPoint(IPAddress.Broadcast, portBack);

                instance = this;
                Handle();
            }
        }

        private void Handle()
        {
            Receive();
        }

        private void Receive()
        {
            for(int i = 0; i + 1 < ports.Length; i++)
            {
                new Thread(() => {
                    Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                    IPEndPoint iep = new IPEndPoint(IPAddress.Any, ports[i]);
                    socket.Bind(iep);
                    EndPoint ep = iep;
                    while (true)
                    {
                        try
                        {
                            byte[] buff = new byte[PacketFileTransport.BytesCount];
                            int rel = socket.ReceiveFrom(buff, ref ep);
                            new Thread(() =>
                            {
                                new ReceivePacket(transportInfo, buff);
                            }).Start();
                        }
                        catch
                        {
                            throw;
                        }
                    }
                }).Start();
                Thread.Sleep(100);
            }
        }

        public void EndReceive(Guid guidTrans)
        {
            if(transportInfo.TransGuid == guidTrans)
            {
                doing = false;
            }
        }

        public void SendBackCheck(PacketFileCheck check)
        {
            socketBack.SendTo(check.ToBytes(), pointBack);
        }
    }
}
